package com.meida.module.arc.provider.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.utils.ApiAssert;
import com.meida.module.arc.client.entity.ArcInfo;
import com.meida.module.arc.client.entity.ArcUse;
import com.meida.module.arc.client.enums.ArchiveEnumInteger;
import com.meida.module.arc.provider.mapper.ArcUseMapper;
import com.meida.module.arc.provider.service.ArcCategoryService;
import com.meida.module.arc.provider.service.ArcInfoService;
import com.meida.module.arc.provider.service.ArcUseService;
import com.meida.module.arc.provider.service.UserUnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 档案利用库接口实现类
 *
 * @author flyme
 * @date 2022-01-06
 */
@Service
@Transactional(rollbackFor = Exception.class)
@DS("sharding")
public class ArcUseServiceImpl extends BaseServiceImpl<ArcUseMapper, ArcUse> implements ArcUseService {

    @Autowired
    private ArcCategoryService arcCategoryService;

    @Autowired
    @Lazy
    private ArcInfoService arcInfoService;

    @Autowired
    private UserUnitService userUnitService;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, ArcUse use, EntityMap extra) {
        return ResultBody.ok();
    }



    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<ArcUse> cq, ArcUse use, EntityMap requestMap) {
        ApiAssert.isNotEmpty("全宗id不能为空", use);
        ApiAssert.isNotEmpty("全宗id不能为空", use.getQzId());
        cq.eq("qzId");
        if (FlymeUtils.isNotEmpty(use)) {
            cq.like("archiveName", use.getArchiveName());
            cq.like("arcNo", use.getArcNo());
            cq.like("categoryName", use.getCategoryName());
        }

        //过滤用户负责机构的数据
//        List<Long> unitIds = userUnitService.getLoginUserUnitIds(use.getQzId());
//        if(FlymeUtils.isNotEmpty(unitIds)){
//            cq.lambda().in(ArcUse::getUnitId,unitIds);
//        }

        cq.lambda().eq(ArcUse::getIsRemove, ArchiveEnumInteger.IS_FALSE.getCode());
        cq.orderByDesc("arcuse.createTime");
        return ResultBody.ok();
    }

    @Override
    public void addArcUse(List<ArcInfo> arcInfos) {
        arcInfos.forEach(item->{
            CriteriaQuery<ArcUse> useCriteriaQuery = new CriteriaQuery<ArcUse>(ArcUse.class);
            useCriteriaQuery.lambda().eq(ArcUse::getArcInfoId,item.getArcInfoId())
                .orderByAsc(ArcUse::getIsRemove);
            List<ArcUse> uses = list(useCriteriaQuery);
            if(FlymeUtils.isEmpty(uses)){
                ArcUse use = new ArcUse();
                use.setOriginalCount(item.getOriginalCount());
                use.setArcInfoId(item.getArcInfoId());
                use.setCategoryId(item.getCategoryId());
                use.setCategoryName(arcCategoryService.getById(item.getCategoryId()).getCnName());
                use.setArchiveName(item.getMaintitle());
                use.setArcNo(item.getArcNo());
                use.setUnitId(item.getUnitId());
                use.setIsRemove(ArchiveEnumInteger.IS_FALSE.getCode());
                use.setQzId(item.getQzId());
                use.setIsUseSubstance(ArchiveEnumInteger.IS_FALSE.getCode());
                this.save(use);
            }else{
                ArcUse use = uses.get(0);
                use.setOriginalCount(item.getOriginalCount());
                use.setArcInfoId(item.getArcInfoId());
                use.setArchiveName(item.getMaintitle());
                use.setArcNo(item.getArcNo());
                use.setUnitId(item.getUnitId());
                use.setIsRemove(ArchiveEnumInteger.IS_FALSE.getCode());
                use.setQzId(item.getQzId());
                this.updateById(use);
                if(uses.size()>1){
                    List<Long> ids = new ArrayList<>();
                    for(int i=1;i<uses.size();i++){
                        ids.add(uses.get(i).getUseId());
                    }
                    ArcUse use1 = new ArcUse();
                    use1.setIsRemove(ArchiveEnumInteger.IS_TRUE.getCode());
                    QueryWrapper<ArcUse> query = new QueryWrapper();
                    query.lambda().in(ArcUse::getUseId,ids);
                    this.update(use1,query);
                }
            }
        });
    }

    @Override
    public ResultBody remove(String useIds) {
        ApiAssert.isNotEmpty("移除对象不能为空",useIds);
        String[] useIdArr = useIds.split(",");
        LambdaQueryWrapper<ArcUse> lambdaQueryWrapper = new LambdaQueryWrapper<ArcUse>();
        lambdaQueryWrapper.in(ArcUse::getUseId, Arrays.stream(useIdArr).map(item->{
            return Long.parseLong(item);
        }).collect(Collectors.toList()));
        List<ArcUse> uses = this.list(lambdaQueryWrapper);
        uses.forEach(item->{
            if(ArchiveEnumInteger.IS_TRUE.getCode().equals(item.getIsUseSubstance())){
                ApiAssert.failure("有未归还的实体借阅，无法移除待借库");
            }
            ArcUse use = new ArcUse();
            use.setUseId(item.getUseId());
            use.setIsRemove(ArchiveEnumInteger.IS_TRUE.getCode());
            this.updateById(use);

            LambdaUpdateWrapper<ArcInfo> upadateWrapper = new LambdaUpdateWrapper<ArcInfo>();
            upadateWrapper.eq(ArcInfo::getCategoryId,item.getCategoryId())
                    .eq(ArcInfo::getArcInfoId,item.getArcInfoId())
                    .set(ArcInfo::getIsUse,ArchiveEnumInteger.IS_FALSE.getCode());
            this.arcInfoService.update(upadateWrapper);
        });
        return ResultBody.ok();
    }
}
